<script setup>
import { useUserStore } from "@/store";
import { onMounted, reactive, ref, toRaw } from "vue";
import { useRouter } from "vue-router";
import { getTeamProfileByKW, addRegInf } from "@/api/teamUp";
import { SUCCESS } from "@/core/constants/HttpStatus";
import { ElMessage } from "element-plus";

const router = useRouter();
const userStore = useUserStore();
const userInfo = userStore.userInfo; //获取当前登录用户信息

//比赛名列表
const competitionList = [
  "全部",
  "全国大学生统计建模大赛",
  "全国大学生市场调查与分析大赛",
  "“中国软件杯”大学生软件设计大赛",
  "中国高校计算机大赛微信小程序开发大赛",
  "粤港澳大湾区IT应用系统开发大赛",
  "全国高校易班技术创新大会应用研发评比大赛",
  "“泰迪杯”数据分析职业技能大赛",
  "“泰迪杯”数据挖掘挑战赛",
  "中国TRIZ杯大学生创新方法大赛",
  "华南农业大学丁颖杯“发明创意大赛”",
  "全国大学生电子商务“创新、创意及创业”挑战赛",
  "华南农业大学“创客杯”创新创业大赛",
  "中国国际“互联网+”大学生创新创业大赛",
  "“挑战杯”广东大学生创业计划竞赛",
  "数字中国创新大赛",
  "华南农业大学大学生创新创业训练计划项目",
  "华南农业大学大学生暑期“三下乡”社会实践活动",
  "其他",
];

//获取队伍数据
const PageSize = 8;
let currentPage = ref(1); // 当前页数
let teamList = ref([]); // 队伍列表
let total = ref(0); // 帖子总数
let pages = ref(0); // 队伍总页数(size=10)
const loading = ref(false);

//搜索表单
const selectForm = reactive({
  isMembersShortage: 0, //人数未满  1：人数未满
  notSignUp: 0, //是否截止  1：未截止
  notCutoff: 0, //是否报名  1：未报名
  projectName: "全部", //比赛名
  kw: "", //搜索词
  uid: "", //用户id
});

//搜索
const loadPage = async (pageNum) => {
  try {
    loading.value = true;
    const res = await getTeamProfileByKW({
      current: pageNum || 1,
      size: PageSize,
      isMembersShortage: selectForm.isMembersShortage,
      notSignUp: selectForm.notSignUp, //是否截止  1：未截止
      notCutoff: selectForm.notCutoff, //是否报名  1：未报名
      projectName: selectForm.projectName, //比赛名
      kw: selectForm.kw, //搜索词
      uid: selectForm.uid,
    });
    const { code, data, msg } = res.data;
    if (code == SUCCESS) {
      teamList.value = data.records;
      total.value = Number(data.total);
      pages.value = Number(data.pages);
    } else {
      throw new Error(msg);
    }
    loading.value = false;
  } catch (error) {
    ElMessage.error(error.message || "搜索队伍失败");
  }
};

onMounted(() => {
  loadPage();
});

//分页
const handleCurrentChange = (val) => {
  currentPage.value = val;
  window.scrollTo(0, 0); //翻页后回到顶部
  loadPage(currentPage.value);
};

//路由跳转
const gotoTeamDetail = (tpId) => {
  const query = { tpId: tpId };
  router.push({ path: "/teamUp/detail", query });
};
const changePageToBuild = () => {
  router.push({ path: "/teamUp/build" });
};
/**
 * 报名板块
 */
//获取当前日期
function getNowFormatDate() {
  let date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1,
    strDate = date.getDate();
  if (month < 10) month = `0${month}`;
  if (strDate < 10) strDate = `0${strDate}`;
  return `${year}-${month}-${strDate}`;
}
let currentDate = getNowFormatDate(); //当前日期
const table = ref(false); //dialog是否显示，默认为否
const selectedTeam = ref(); //要报名的队伍

const showDialog = (teamItem) => {
  Object.assign(signForm, toRaw(originalSignForm));
  table.value = true;
  selectedTeam.value = teamItem;
  signForm.ri_team_id = teamItem.tpId;
};
const signFormRef = ref(null);
const originalSignForm = reactive({
  ri_uid: userInfo.uid, //学号
  ri_realname: userInfo.urealname, //真实姓名
  ri_grade: "", //年级
  ri_major: "", //专业
  ri_contact: "", //联系方式
  ri_intro: "", //个人简介
  ri_team_id: "", //报名队伍ID
});
const signForm = reactive({
  ri_uid: userInfo.uid, //学号
  ri_realname: userInfo.urealname, //真实姓名
  ri_grade: "", //年级
  ri_major: "", //专业
  ri_contact: "", //联系方式
  ri_intro: "", //个人简介
  ri_team_id: "", //报名队伍ID
});
const signFormRules = {
  ri_grade: [
    { required: true, message: "请输入年级", trigger: "blur" },
    {
      pattern: /^\d{4}$/,
      message: "年级应为四位数字，如：2021",
      trigger: "blur",
    },
  ],
  ri_major: [
    { required: true, message: "请输入专业", trigger: "blur" },
    {
      pattern: /^[\u4e00-\u9fa5]+$/,
      message: "专业应为中文字符",
      trigger: "blur",
    },
  ],
  ri_contact: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
};
const signUp = async () => {
  await signFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await addRegInf(signForm);
        console.log(res);
        const { code, data, msg } = res.data;
        if (code == SUCCESS) {
          if (msg == "报名成功!") {
            ElMessage.success("报名成功");
            table.value = false;
            Object.assign(signForm, toRaw(originalSignForm));
          } else {
            ElMessage.error(msg);
          }
        } else {
          throw new Error(msg);
        }
      } catch (error) {
        ElMessage.error(error.message || "报名失败");
      }
    } else {
      ElMessage.error("请重新检查是否有缺漏信息");
    }
  });
};
//修改teamInfo中的<br/>为空格
const replaceBrWithSpaces = (text) => {
  return text.replace(/<br\s*\/?>/gi, " ");
};
</script>
<template>
  <!--组队大厅-->
  <div class="team-main">
    <!-- 顶部搜索栏 -->
    <div class="select-box" @keyup.enter="loadPage()">
      <el-input
        v-model="selectForm.kw"
        placeholder="Please input"
        class="input-with-select"
      >
        <template #prepend>
          <el-select v-model="selectForm.projectName" style="width: 115px">
            <el-option label="全部" value="全部" />
            <el-option label="大创" value="大创" />
            <el-option label="数模" value="数模" />
            <el-option label="挑战杯" value="挑战杯" />
            <el-option label="丁颖杯" value="丁颖杯" />
            <el-option label="三下乡" value="三下乡" />
            <el-option label="互联网+" value="互联网+" />
            <el-option label="统计建模" value="统计建模" />
          </el-select>
        </template>
        <template #append>
          <el-button @click="loadPage()"
            ><i class="iconfont icon-sousuo"></i
          ></el-button>
        </template>
      </el-input>
      <el-button class="organize-team" @click="changePageToBuild">
        发布招募</el-button
      >
      <div class="check-box">
        <el-checkbox
          label="人数未满"
          name="type"
          v-model="selectForm.isMembersShortage"
          :true-label="1"
          :false-label="0"
        />
        <el-checkbox
          label="未报名"
          name="type"
          v-model="selectForm.notSignUp"
          :true-label="1"
          :false-label="0"
        />
        <el-checkbox
          label="未截止"
          name="type"
          v-model="selectForm.notCutoff"
          :true-label="1"
          :false-label="0"
        />
      </div>
    </div>

    <!-- 侧边跳转页面图标 -->
    <router-link class="iconfont icon-zhaomu" to="/teamUp/build"></router-link>

    <!-- 招募队伍信息 -->
    <div v-loading="loading">
      <ul class="team-display" v-if="teamList.length > 0">
        <li
          class="team-intro"
          v-for="(teamItem, index) in teamList"
          :key="index"
        >
          <!-- 队伍信息 左侧图标-->
          <div class="left-box">
            <i class="iconfont icon-shuzhuangtu"></i>
          </div>
          <!-- 队伍信息 中部文本内容 -->
          <div class="middle-box" @click="gotoTeamDetail(teamItem.tpId)">
            <h4>{{ teamItem.tpProjectName }}</h4>
            <h3>{{ teamItem.tpTeamName }}</h3>
            <p class="detail-message">
              {{ replaceBrWithSpaces(teamItem.tpTeamIntro) }}
            </p>
            <p class="time">
              截止于<span>{{ teamItem.tpRegistrationDeadline }}</span>
            </p>
          </div>
          <!-- 队伍信息 右侧按钮等-->
          <div class="right-box">
            <div class="member-number">
              <b>{{ teamItem.tpMemberNumber }}</b>
              /
              <b>{{ teamItem.tpNeedStudentNumber }}</b>
              <i class="iconfont icon-yaoqinghaoyou"></i>
            </div>
            <div class="router-box">
              <button
                class="iconfont icon-icon-"
                @click="gotoTeamDetail(teamItem.tpId)"
              >
                查看详情
              </button>
              <el-button
                class="stop-button"
                v-if="currentDate > teamItem.tpRegistrationDeadline"
                type="warning"
                text
                disabled
                >已截止</el-button
              >
              <el-button
                class="filled-button"
                type="success"
                v-else-if="
                  teamItem.tpMemberNumber >= teamItem.tpNeedStudentNumber
                "
                text
                disabled
                >已满员</el-button
              >
              <button
                v-else
                class="iconfont icon-baoming"
                @click="showDialog(teamItem)"
              >
                我要报名
              </button>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <!-- 报名侧边抽屉 -->
    <el-drawer
      v-model="table"
      class="sign-box"
      v-if="selectedTeam"
      :title="'队伍报名---' + selectedTeam.tpTeamName"
      direction="rtl"
      size="50%"
    >
      <el-form
        class="sign-form"
        ref="signFormRef"
        :rules="signFormRules"
        :model="signForm"
      >
        <el-row>
          <el-form-item label="学号："
            ><el-input v-model="signForm.ri_uid" disabled></el-input
          ></el-form-item>
          <el-form-item label="姓名："
            ><el-input v-model="signForm.ri_realname" disabled></el-input
          ></el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="年级：" prop="ri_grade"
            ><el-input v-model="signForm.ri_grade"></el-input
          ></el-form-item>
          <el-form-item label="专业：" prop="ri_major"
            ><el-input v-model="signForm.ri_major"></el-input
          ></el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="联系方式：" class="contact" prop="ri_contact"
            ><el-input v-model="signForm.ri_contact"></el-input
          ></el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="个人简介：" class="personal-intro"
            ><el-input
              v-model="signForm.ri_intro"
              type="textarea"
              :rows="10"
            ></el-input
          ></el-form-item>
        </el-row>
        <el-row>
          <el-form-item class="button">
            <el-button @click="table = false">取消</el-button>
            <el-button type="primary" @click="signUp">提交</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-drawer>
    <!-- 分页组件 -->
    <div class="bottom-box">
      <template v-if="teamList.length">
        <el-pagination
          class="pagination"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :total="total"
          :page-size="PageSize"
          :hide-on-single-page="false"
        >
        </el-pagination>
      </template>
      <template v-else>
        <div class="no-content-tip">暂无数据</div>
      </template>
    </div>
  </div>
</template>

<style scoped lang="less">
.team-main {
  height: auto;
  width: 70%;
  //顶部搜索栏
  .select-box {
    width: 100%;
    display: grid;
    grid-template-columns: 700px 100px;
    align-items: center;
    justify-content: center;
    margin-top: 10px;
    font-size: 16px;
    .input-with-select {
      width: 700px;
      margin: 0px auto;
    }
    .check-box {
      margin-left: 15px;
    }
    .organize-team {
      margin-left: 15px;
      width: 100px;
      .no-color-link {
        color: inherit;
        text-decoration: none;
      }
    }
  }
  //侧边图标（跳转至发布招募）
  .icon-zhaomu {
    position: fixed;
    cursor: pointer;
    top: 250px;
    right: 15px;
    font-size: 50px;
    color: white;
    border-radius: 50%;
    padding: 8px;
    background-color: #0066c0;
    text-decoration: none;
  }
  .team-display {
    margin-top: 10px;
    .team-intro {
      display: grid;
      grid-template-columns: 90px auto 140px;
      border-bottom: 1px dashed black;
      padding: 10px 0px;
      margin-top: 10px;
      // 左侧图标
      .left-box {
        margin: 5px 20px;
        .icon-shuzhuangtu {
          font-size: 50px;
          color: #0d7f99;
        }
      }
    }
  }
}

//中部文本内容
.middle-box {
  text-align: left;
  padding-right: 20px;

  //grid布局
  display: grid;
  grid-template-rows: 25px 30px 38px 25px;
  .detail-message {
    font-size: 15px;
    // 文本超出第二行末尾显示...
    display: -webkit-box;
    -webkit-line-clamp: 2; /* 设置显示的行数 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: break-word;
  }
  .time {
    color: #b4abaf;
    font-size: 13px;
    margin-top: 10px;
  }
}

//右侧盒子
.right-box {
  display: grid;
  grid-template-rows: 40px 80px;
  margin: 0px 10px 0px 20px;
  //队伍人数
  .member-number {
    width: 100px;
    font-size: 20px;
    align-self: flex-start;
    .icon-yaoqinghaoyou {
      font-size: 24px;
      margin-left: 15px;
    }
  }
  //跳转路由
  .router-box {
    width: 100px;
    align-self: flex-end;
    display: flex;
    flex-direction: column;
    margin-top: 25px;
    .icon-icon-,
    .icon-baoming {
      height: 30px;
      width: 100px;
      margin: 2px 0px;
      font-size: 13px;
      border-radius: 5px;
      border: 1px solid #e2e4ea;
      background-color: white;
      color: #716c71;
    }
    .stop-button,
    .filled-button {
      height: 30px;
      margin: 2px 0px;
      padding: 2px 5px;
    }
    //鼠标移入效果
    .icon-icon-:hover,
    .icon-baoming:hover {
      color: white;
      background-color: #5098a8;
    }
  }
}
// 报名弹窗
.sign-box {
  .sign-form {
    width: 90%;
    margin: 0px auto;
    .el-row {
      display: flex;
      justify-content: center;
      .el-form-item {
        width: 45%;
        margin-right: 2%;
      }
      .el-form-item:last-child {
        margin-right: 0;
      }
      .contact,
      .personal-intro {
        width: 95%;
      }
      .button {
        width: auto;
        margin-top: 2%;
        .el-button {
          width: 120px;
        }
        .el-button:first-child {
          margin-right: 10px;
        }
      }
    }
  }
}
.no-content-tip {
  line-height: 100px;
  text-align: center;
  font-size: 18px;
  margin-top: 50px;
}
</style>
